<?php

namespace app\admin\controller;

use app\admin\controller\user\User;
use app\api\command\CategoryBuild;
use app\common\controller\Backend;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 房产认证管理
 *
 * @icon fa fa-circle-o
 */
class RoomCheck extends Backend
{
    
    /**
     * RoomCheck模型对象
     * @var \app\admin\model\RoomCheck
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\RoomCheck;
        $this->view->assign("typedataList", $this->model->getTypedataList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->with(['user','site'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','site'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $param = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['province_id'] = $param['province_id'];
                $params['city_id'] = $param['city_id'];
                $params['area_id'] = $param['area_id'];
                $params['town_id'] = $param['town_id'];
                $params['site_id'] = $param['site_id'];
                if(!empty($param['site_id'])){
                    $params['sitename'] = Db::name('user')->where('id',$param['site_id'])->value('sitename');
                }
                $this->roomValidate($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $param = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['province_id'] = $param['province_id'];
                $params['city_id'] = $param['city_id'];
                $params['area_id'] = $param['area_id'];
                $params['town_id'] = $param['town_id'];
                $params['site_id'] = $param['site_id'];
                if(!empty($param['site_id'])){
                    $param['sitename'] = Db::name('user')->where('id',$param['site_id'])->value('sitename');
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row->province_name = db('area2')->where('id',$row->province_id)->value('name');
        $row->city_name = db('area2')->where('id',$row->city_id)->value('name');
        $row->area_name = db('area2')->where('id',$row->area_id)->value('name');
        $row->town_name = db('area2')->where('id',$row->town_id)->value('name');
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * Notes: 审核
     * User: hawk
     * Email: 2271030162@qq.com
     * Date: 2019/6/20 0020
     * Time: 17:39
     */
    public function check(){
        $id = input('ids');
        $status = input('status');
        $roomCheckModel = new \app\admin\model\RoomCheck();
        $roomCheckInfo = $roomCheckModel->find($id);
        if($roomCheckInfo->status>1){
            $this->error('该条审核已处理');
        }
        if(empty($roomCheckInfo)){
            $this->error('数据过期，请刷新重试');
        }
        if($status==1){
            $site_info = Db::name('area2')
                ->alias('a')
                ->join('user u','u.id=a.site_id')
                ->where('a.id',$roomCheckInfo['site_area_id'])
                ->find();
            if($site_info)$this->error('此行政站已被认证');
            Db::startTrans();
            try{
                $roomCheckInfo->status = '2';
                $roomCheckInfo->checktime = time();
                //$roomCheckInfo->site_id = $roomCheckInfo->user_id;
                $result = $roomCheckModel->save(['status'=>2,'checktime'=>time()],['id'=>$roomCheckInfo->id]);
                if($roomCheckInfo->typedata=='2'){
                    $user = new \app\admin\model\User();
                    $userInfo = $user->get($roomCheckInfo['user_id']);
                    $userInfo->is_check  ='1';
                    $userInfo->checkdata ='1';
                    $areaFour = [];
                    //修改会员信息
                    if($roomCheckInfo->town_id){
                        $areaFour = db('area2')->where('id',$roomCheckInfo->town_id)->find();
                        if(empty($areaFour)){
                            $areaFour = db('area2')->where('id',$roomCheckInfo->area_id)->find();
                            if(empty($areaFour)){
                                $areaFour = db('area2')->where('id',$roomCheckInfo->city_id)->find();
                                if(empty($areaFour)){
                                    $areaFour = db('area2')->where('id',$roomCheckInfo->province_id)->find();
                                }
                            }
                        }
                    }
                    $updateData = ['is_check'=>'1','checkdata'=>'1'];
                    if($areaFour){
                        $userInfo->area_str = $areaFour['whole_name'];
                        $updateData['whole_name'] = $areaFour['whole_name'];
                    }
                    $user->allowField(true)->save($updateData,['id'=>$userInfo->id]);
                    if($userInfo->site_type==1){
                        Db::name('area2')->where('id',$roomCheckInfo->site_area_id)->update(['is_site'=>1,'site_id'=>$roomCheckInfo['user_id']]);
                    }
                    //开站长后台账号
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5(substr($userInfo->mobile,-6)) . $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $params['username'] = $userInfo->username;
                    $params['nickname'] = $userInfo->sitename;
                    $params['site_id'] = $userInfo->id;
                    $adminModel = new \app\admin\model\Admin();
                    $result = $adminModel->save($params);
                    //创建基础分类
                    (new \app\admin\model\Category())->createSiteNav($userInfo->id);
                    model('AuthGroupAccess')->save(['uid'=>$adminModel->id,'group_id'=>6]);
                }elseif ($roomCheckInfo->typedata=='1'){
                    $userModel = new \app\admin\model\User();
                    $data = [
                        'is_check'  =>'1',
                        'checkdata' => '1',
                    ];
                    $result = $userModel->save($data,['id'=>$roomCheckInfo['user_id']]);
                    $result = db('user_site')->insert(['user_id'=>$roomCheckInfo['user_id'],'site_id'=>$roomCheckInfo['site_id']]);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('系统故障:'.$e->getMessage());
            }
            if($result){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }

        }elseif ($status==2){
            Db::startTrans();
            try{
                $result = $this->model->save(['status'=>'3','checktime'=>time()],['id'=>$id]);
                $roomCheckModel = new \app\admin\model\RoomCheck();
                $user = new \app\admin\model\User();
                $roomCheckInfo = $roomCheckModel->find($id);
                if($roomCheckInfo->typedata=='2'){
                    $user->where('id',$roomCheckInfo['user_id'])->setField('checkdata',2);
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error('系统故障');
            }
            if($result){
                $this->success('操作成功');
            }else{
                $this->error('操作成功');
            }
        }else{
            $this->error('无此操作');
        }
    }

    private function roomValidate($param){
        $userModel = new \app\admin\model\User();
        $userInfo = $userModel->where('id',$param['user_id'])->find();
        if($userInfo->group_id==2 && $userInfo['site_level']!=5){
            $this->error('业主会员仅可认证基础站点');
        }
        if($userInfo->group_id==2){
            $roomCheckNumber2 = $this->model->where('user_id',$userInfo->id)->where('site_id',$param['site_id'])->where('status','2')->where('typedata','1')->find();
            if($roomCheckNumber2)$this->error('此站点已认证');
        }
        if($userInfo->group_id>2){
            $roomCheckNumber = $this->model->where('user_id',$userInfo->id)->where('status','2')->where('typedata','1')->find();
            if($roomCheckNumber)$this->error('已认证请勿重复提交');
        }
        return true;
    }
}
